package com.huixue.cn.ztej.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huixue.cn.ztej.bean.LoginLogger;
import com.huixue.cn.ztej.bean.Project;
import com.huixue.cn.ztej.bean.Resource;
import com.huixue.cn.ztej.bean.Results;
import com.huixue.cn.ztej.bean.RoleResource;
import com.huixue.cn.ztej.bean.User;
import com.huixue.cn.ztej.constants.UserUtil;
import com.huixue.cn.ztej.dao.LoginLoggerMapper;
import com.huixue.cn.ztej.dao.RoleResourceMapper;
import com.huixue.cn.ztej.dao.UserMapper;
import com.huixue.cn.ztej.utils.HashMapUtil;
import com.huixue.cn.ztej.utils.MD5;
import com.huixue.cn.ztej.utils.SystemContents.API_RETURN_STATUS;
import com.huixue.cn.ztej.utils.framwork.PageParameter;


@Service
public class SysUserService {
	
	private static Logger logger = LoggerFactory.getLogger(SysUserService.class);
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private LoginLoggerMapper loginLogMapper;
	
	@Autowired
	private RoleResourceMapper roleResourceDao;
	
	public Results userLogin(HttpServletRequest request,String username, String password, String ip) {
		Results results = new Results(API_RETURN_STATUS.NORMAL.value()
				,API_RETURN_STATUS.NORMAL.desc());
		String result = "login";
		User currentUser = userMapper.findByLoginName(username);
			System.out.println("md5====="+MD5.md5(password));
		try {
//			//登录验证
			if(currentUser==null){//用户不存在
				result = "/sys/toLogin";
				results.setStatus(API_RETURN_STATUS.USER_NOT_EXIST.value());
				results.setError(API_RETURN_STATUS.USER_NOT_EXIST.desc());
				results.setData(result);
				return results;
			}else if(!currentUser.getPassword().equals(MD5.md5(password))){//密码错误
				result = "/sys/toLogin";
				results.setStatus(API_RETURN_STATUS.PASSWORD_ERROR.value());
				results.setError(API_RETURN_STATUS.PASSWORD_ERROR.desc());
				results.setData(result);
				return results;
			}else if(currentUser.getIsAvailable()==0){
				result = "/sys/toLogin";
				results.setStatus(API_RETURN_STATUS.USER_DISABLE.value());
				results.setError(API_RETURN_STATUS.USER_DISABLE.desc());
				results.setData(result);
				return results;
			}
			
			//获取用户权限
			List<RoleResource> rResList = roleResourceDao.findResourceByRole(Integer.valueOf(currentUser.getRoleId()));
			if(rResList!=null && rResList.size()>0){
				List<RoleResource> tickerList = new ArrayList<RoleResource>();
				for(RoleResource rrs:rResList){
					if(rrs.getResource().getParentId()==-1){
						tickerList.add(rrs);
					}
				}
				
				if(tickerList.size()>0 && rResList.size()>0){
					for(RoleResource rs:tickerList){
						getchildren(rs, rResList);
					}
				}
				request.getSession().setAttribute("ticker",tickerList);
			}
			//保存用户登录日志
			LoginLogger logger = new LoginLogger(currentUser.getLoginName(),
					currentUser.getUserName(),ip,new Date(),1);
			//loginLogMapper.addLogger(logger);
			
			request.getSession().setAttribute("loginUser",currentUser);
			request.getSession().setAttribute("loginUserName",currentUser.getUserName());
			request.getSession().setAttribute("loginAccount",currentUser.getLoginName());
			request.getSession().setAttribute("loginTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
			result = "/sys/toIndex";
			results.setData(result);
		} catch (Exception e) {
			result = "/sys/toLogin";
			logger.error(e.getMessage());
			results.setStatus(API_RETURN_STATUS.SERVER_INTERNAL_ERROR.value());
			results.setError(API_RETURN_STATUS.SERVER_INTERNAL_ERROR.desc());
			results.setData(result);
			e.printStackTrace();
		}
		return results;
		
	}
	
	public User findUserByLoginName(String loginName){
		User currentUser = userMapper.findByLoginName(loginName);
		return currentUser;
	}
	
	public User findUserById(Integer userId){
		User currentUser = userMapper.findById(userId);
		return currentUser;
	}
	
	public void saveUser(User us){
		userMapper.saveUser(us);
	}
	
	public void updateUser(User user){
		userMapper.updateByPrimaryKey(user);
	}
	
	public Results searchUserByPage(Map<String,Object> searchParams,Integer pageNumber, Integer pageSize) {
		PageParameter page = new PageParameter();
		page.setCurrentPage(pageNumber);
		page.setPageSize(pageSize);
		searchParams.put("page", page);
		searchParams.put("status", new Integer(1));
		
		List<User> list = userMapper.searchByPage(searchParams);
		
		Map<String, Object> rmap = new HashMap<String, Object>();
		rmap.put("total", page.getTotalPage());
		rmap.put("page", pageNumber);						//当前页
		rmap.put("records", page.getTotalCount());			//总记录数
		rmap.put("pageSize", pageSize);						//每页个数
		
		rmap.put("rows", list);
		Results results = new Results(
				API_RETURN_STATUS.NORMAL.value(),
				API_RETURN_STATUS.NORMAL.desc(),rmap);
		return results;
	}
	
	public User findUserByOpenId(String openId) {
		User currentUser;
		if(HashMapUtil.openIDMap.get(openId)!=null){
			currentUser = HashMapUtil.openIDMap.get(openId);
		}else{
			currentUser = userMapper.findByOpenId(openId);
			if(currentUser!=null){
				HashMapUtil.openIDMap.put(openId, currentUser);
			}
		}
		return currentUser;
	}
	
	public User findUserByOpenId(String openId,boolean flag) {
		User currentUser = null;
		
		if(flag){
			if(HashMapUtil.openIDMap.get(openId)!=null){
				currentUser = HashMapUtil.openIDMap.get(openId);
			}
		
			if(currentUser==null){
				currentUser = userMapper.findByOpenId(openId);
			}
			
			if(currentUser!=null){
				HashMapUtil.openIDMap.put(openId, currentUser);
			}
		}else{
			currentUser = userMapper.findByOpenId(openId);
			if(currentUser!=null){
				HashMapUtil.openIDMap.put(openId, currentUser);
			}
		}
		
		return currentUser;
	}
	
	public User findUserByParams(Map<String,Object> searchParams){
		User user = null;
		List<User> listUser  = userMapper.findUserByParams(searchParams);
		if(listUser!=null && listUser.size()>0){
			user = listUser.get(0);
		}
		return user;
	}
	
	
	public RoleResource getchildren(RoleResource rrs,List<RoleResource> list){
		if(list.size()>0 && rrs.getResource().getType()==1){
			List<RoleResource> childlist = new ArrayList<RoleResource>();
			rrs.getResource().setHavechild(0);
			for(RoleResource rse:list){
				if(rse.getResource().getParentId() ==rrs.getResource().getResourceId()){
					childlist.add(rse);
					if(rse.getResource().getType()==1 && list.size()>0){
						rse = getchildren(rse, list);
					}
				}
			}
			if(childlist.size()>0){
				rrs.getResource().setHavechild(1);
				rrs.getResource().setrRoleList(childlist);
			}
			
		}
		return rrs;
	}
	
	public void deleteforuser(User user){
		userMapper.deleteforuser(user);
	}
	
	public Boolean haveUserForList(List<User> items){
		Boolean b = false;
		List<User> list = userMapper.haveUserForList(items);
		if(list!=null && list.size()>0){
			b = true;
		}
		return b;
	}
	
	public void batchInsertUser(List<User> items){
		userMapper.batchInsertUser(items);
	}
}
